using Digitalmes.Application.Scada.Events;
using Digitalmes.Application.Scada.Models;
using Digitalmes.Application.Scada.Services;

namespace Digitalmes.Application.Scada.Commands;

/// <summary>
/// 出站请求命令处理者。
/// </summary>
internal sealed class OutboundCommandHandler(IPublisher publisher, IServiceScopeFactory serviceScopeFactory) : IRequestHandler<OutboundCommand, ScadaResult>
{
    public async Task<ScadaResult> Handle(OutboundCommand request, CancellationToken cancellationToken)
    {
        using var scope = serviceScopeFactory.CreateScope();
        var service = scope.ServiceProvider.GetRequiredService<IOutboundService>();
        OutboundInput input = new(request.LineCode, request.WsCode, request.SN, request.PassResult, request.CycleTime, request.AttachData);
        var result = await service.ArchiveAsync(input, cancellationToken).ConfigureAwait(false);

        // 处理成功后发布产品存档后处理事件（不等待）
        if (result.IsSuccess() && result.Target is OutboundOutput output)
        {
            await publisher.Publish(new AfterOutboundEvent(output), cancellationToken).ConfigureAwait(false);
        }

        return result;
    }
}
